package com.app.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;

import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import ReadWriteXML.CMember;
import ReadWriteXML.XMLBuilder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;

import com.app.Controller.ActivityController;
import com.app.Controller.NetworkController;
import com.app.Controller.ReadWriteFileController;
import com.app.DTO.RoleDTO;
import com.app.Network.Protocol;
import com.app.Tree.BoardView;
import com.app.Tree.INode;
import com.app.Tree.TextNode;
import com.app.Tree.TreeNode;
import com.app.outdoor.InvoikeServices.CommonInvoike;
import com.app.outdoor.InvoikeServices.HeThongInvoike;
import com.app.outdoor.pojo.NguoiDungPOJO;
import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

	Handler handler;
	private static final String TAG = "GCMIntentService";

	public GCMIntentService() {
		super(Protocol.SENDER_ID);
		handler = new Handler();
	}

	@Override
	protected void onRegistered(Context context, String registrationId) {
		Log.i(TAG, "Device registered: regId = " + registrationId);
		HeThongInvoike.register(context);
	}

	@Override
	protected void onUnregistered(Context context, String registrationId) {
		Log.i(TAG, "Device unregistered");

	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		Log.i(TAG, "onMessage");
		String type = intent.getStringExtra(Protocol.CMD) + "";
		Log.i(TAG, "onMessage type=" + type);
		if (type.equals(Protocol.DANG_NHAP)) {
			int idNguoiDung = Integer.parseInt(intent.getStringExtra(Protocol.ID));
			String tenDangNhap = intent.getStringExtra(Protocol.TEN_DANG_NHAP);
			Log.d("id-tendangnhap", idNguoiDung + "-" + tenDangNhap);
			if (CommonUtilities.nguoiDung == null) {
				CommonUtilities.nguoiDung = new NguoiDungPOJO();
			}
			CommonUtilities.nguoiDung.setId(idNguoiDung);
			CommonUtilities.nguoiDung.setTenDangNhap(tenDangNhap);
		} else if (type.equals(Protocol.TAO_CAY)) {

			int idCay = Integer.parseInt(intent.getStringExtra(Protocol.ID_CAY).trim());
			int idNguoiGui = Integer.parseInt(intent.getStringExtra(Protocol.NGUOI_GUI));
			int idNhom = Integer.parseInt(intent.getStringExtra(Protocol.ID_NHOM));
			if (idNguoiGui != CommonUtilities.nguoiDung.getId()) {
				ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair(Protocol.ID_CAY, idCay + ""));
				params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, idNguoiGui + ""));
				params.add(new BasicNameValuePair(Protocol.ID_NHOM, idNhom + ""));
				notification(context, "Có 1 thảo luận mới!", od_VaoThaoLuanActivity.class, params);

				CommonUtilities.idCayHienTai = idCay;
			}

		} else if (type.equals(Protocol.JOIN_GROUP)) {
			String id = intent.getStringExtra(Protocol.NGUOI_GUI);
			CMember member = new CMember(id, id, id);
			frmNhomChoActivity.insertMember(member);

			final ArrayList<CMember> memberList = ReadWriteFileController
					.readMember(ReadWriteFileController.MEMBER_PATH);
			String ids = "";
			for (CMember m : memberList) {
				ids += m.get_ip() + ";";
			}

			try {
				// Gửi danh sách nhóm hiện tai cho thanh vien moi join
				CommonInvoike.guiTinNhan(CommonUtilities.nguoiDung.getId() + "", id, ids, Protocol.MEMBER_LIST);
				// Gửi id của người vừa mới join cho các thành viên khác
				for (int i = 0; i < memberList.size(); i++) {
					String toId = memberList.get(i).get_ip();
					if (!id.equals(toId)) {
						CommonInvoike.guiTinNhan(CommonUtilities.nguoiDung.getId() + "", toId, id,
								Protocol.UPDATE_MEMBER_LIST);
					}
				}
			} catch (Exception e) {
				Log.d(TAG, "Không gửi đc msg update member list tới các thành viên \n" + e.getMessage());
				e.printStackTrace();
			}

			handler.post(frmNhomChoActivity.raRefreshListView);
			Log.d(TAG, "nguoi gui id=" + id + " danh sach thanh vien =" + ids);
		} else if (type.equals(Protocol.UPDATE_MEMBER_LIST)) {
			String id = intent.getStringExtra(Protocol.NOI_DUNG);
			int idNguoiGui = Integer.parseInt(intent.getStringExtra(Protocol.NGUOI_GUI).trim());
			if (idNguoiGui != CommonUtilities.nguoiDung.getId()) {
				CMember member = new CMember(id, id, id);
				frmNhomChoActivity.insertMember(member);
			}
		} else if (type.equals(Protocol.MEMBER_LIST)) {

			int idNguoiGui = Integer.parseInt(intent.getStringExtra(Protocol.NGUOI_GUI).trim());
			if (idNguoiGui != CommonUtilities.nguoiDung.getId()) {
				String ids = intent.getStringExtra(Protocol.NOI_DUNG);
				Log.d(TAG, "member list=" + ids);
				String[] m = ids.split(";");
				int id;
				String userName;
				
				ReadWriteFileController.deleteFile(ReadWriteFileController.MEMBER_PATH);
				for (int i = 0; i < m.length; i++) {
					CMember member = new CMember(m[i], m[i], m[i]);
					frmNhomChoActivity.insertMember(member);
				}
				int idNhom = CommonUtilities.idNhomHienTai;
				Intent i = new Intent(context, frmNhomChoActivity.class);
				i.putExtra(frmTaoNhom.CODE_GROUP_NAME, CommonUtilities.contacts.getGroup(idNhom).getTenNhom());
				NetworkController.setGroupName(CommonUtilities.contacts.getGroup(idNhom).getTenNhom());
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(i);
			}
		} else if (type.equals(Protocol.SET_ROLE)) {
			String noiDung = intent.getStringExtra(Protocol.NOI_DUNG);
			String path = ReadWriteFileController.MY_ROLE_PATH;
			ReadWriteFileController.writeRole(path,
					RoleDTO.parseList(MESApplication.getAppContext(), noiDung, ReadWriteFileController.RULE_BASE_PATH));
			NetworkController.resetRole();
		} else if (type.equals(Protocol.START_GROUP)) {
			NetworkController._peer.getAccount().inGroup = true;
			handler.post(frmNhomChoActivity.raStartGroup);
		}else if(type.equals(Protocol.THEM_NODE)){
			String noiDung=intent.getStringExtra(Protocol.NOI_DUNG);
			Log.d(TAG, noiDung);
				Document doc=null;
				try {
					doc = XMLBuilder.loadXMLFromString(noiDung);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				Element e=(Element) doc.getElementsByTagName("TreeNode").item(0);
				TreeNode node=new TreeNode();
				TextNode textnode=new TextNode();
				
				node.readXML(e);
				textnode.readXML(e);
				
				int idNguoiTao=Integer.parseInt(node.getUser());
				NguoiDungPOJO nd=CommonUtilities.contacts.getNguoiDungByID(idNguoiTao);
				
				node.setUser(nd.getTenDangNhap());
				textnode.setUser(nd.getTenDangNhap());
				frmTreeNodeActivity.idNode=node.getParentID();
				frmTreeNodeActivity.nodeAdd=node;
				frmTreeNodeActivity.textnodeAdd=textnode;
				Log.d("Phu"," NetWorkLayer-AddNode..." + frmTreeNodeActivity.isActive);
				if(frmTreeNodeActivity.isActive){
					Log.d("Phu"," NetWorkLayer-AddNode...active nen cho vao cay luon");
					handler.post(frmTreeNodeActivity.raAddnode);
					handler.post(frmTreeNodeActivity.raAddnodetext);
				}
				else{
					Log.d(TAG,"GCMIntentService-AddNode...ko active nen ghi xuong file node: " + node.getId());					
					TreeNode tree = new TreeNode();
					if(ReadWriteFileController.isFile(BoardView.treePath)){							
						tree.readXml(BoardView.treePath);
						Log.d(TAG,"GCMIntentService-AddNode...File tồn tại nên đọc từ file lên: "+tree.getSumChildren());
					}else{
						Log.d(TAG,"GCMIntentService-AddNode...Ko tồn tại file nên createRoot: "+tree.getSumChildren());
						tree=BoardView.createRoot();
					}
					INode temp = tree.getById(node.getParentID());
					if (temp != null){
						Log.d(TAG,"GCMIntentService-AddNode...add node: " + node.getId()+" vào node " + temp.getId());
						temp.add(node);
						tree.setVersion(node.getVersion());
						Log.d(TAG,"GCMIntentService-AddNode...add node: " + tree.getSumChildren());
					}
					tree.writeXML(BoardView.treePath);
				}
			
			
		}else if(type.equals(Protocol.XOA_NODE)) {
			try {
				String s = intent.getStringExtra(Protocol.NOI_DUNG);
				INode node = new TreeNode();
				INode tnode = new TextNode();
				Document doc;

				doc = XMLBuilder.loadXMLFromString(s);

				Element e = (Element) doc.getElementsByTagName("TreeNode").item(0);
				node.readXML(e);
				tnode.readXML(e);
				String nguoiTao=CommonUtilities.contacts.getNguoiDungByID(Integer.parseInt(node.getUser())).getTenDangNhap();
				node.setUser(nguoiTao);
				tnode.setUser(nguoiTao);
				frmTreeNodeActivity.nodeAdd = (TreeNode) node;
				frmTreeNodeActivity.textnodeAdd = (TextNode) tnode;
				if (frmTreeNodeActivity.isActive) {
					Log.d("An", "active nên delete luôn");
					handler.post(frmTreeNodeActivity.raDeleteNode);
					handler.post(frmTreeNodeActivity.raDeleteNodeText);
				} else {
					Log.d("An", "delete ko active nên xóa ghi xuống file");

					TreeNode tree = new TreeNode();
					tree.readXml(BoardView.treePath);
					INode temp = tree.getById(node.getId());
					if (temp != null) {
						tree.remove(temp);
						tree.setVersion(node.getVersion());
						tree.writeXML(BoardView.treePath);
					}

				}
			} catch (Exception e1) {
				Log.d(TAG,"GCMIntentService - Không thể Xóa node");
				Log.d(TAG, e1.getMessage());
				e1.printStackTrace();
			}
		}else if(type.equals(Protocol.CAP_NHAT_NODE)){
			try {
				String s = intent.getStringExtra(Protocol.NOI_DUNG);
				TreeNode node = new TreeNode();
				TextNode textnode = new TextNode();
				Document doc = XMLBuilder.loadXMLFromString(s);
				Element e = (Element) doc.getElementsByTagName("TreeNode").item(0);
				node.readXML(e);
				textnode.readXML(e);
				String nguoiTao=CommonUtilities.contacts.getNguoiDungByID(Integer.parseInt(node.getUser())).getTenDangNhap();
				node.setUser(nguoiTao);
				textnode.setUser(nguoiTao);
				// frmTreeNodeActivity.idNode=node.getId();
				// frmTreeNodeActivity.textUpdate=node.getText();
				// frmTreeNodeActivity.lb = node.getLabel();
				frmTreeNodeActivity.nodeAdd = node;
				frmTreeNodeActivity.textnodeAdd = textnode;
				if (frmTreeNodeActivity.isActive) {
					Log.d("Phu", "Active nên update vào cây luôn");
					handler.post(frmTreeNodeActivity.raUpdateTextNode);
					handler.post(frmTreeNodeActivity.raUpdateNodeText);
				} else {
					Log.d("Phu", "update ko active cap nhat xuong file");
					TreeNode tree = new TreeNode();
					if (ReadWriteFileController.isFile(BoardView.treePath)) {
						tree.readXml(BoardView.treePath);
					} else {
						tree = BoardView.createRoot();
					}
					INode temp = tree.getById(node.getId());
					if (temp != null) {
						temp.copy(node);
					}
					tree.writeXML(BoardView.treePath);
				}
			} catch (Exception e) {
				Log.d(TAG,"GCMIntentService - Không thể cập nhật node");
				Log.d(TAG, e.getMessage());
			}
		}
		
	}

	@Override
	protected void onDeletedMessages(Context context, int total) {
		Log.i(TAG, "Received deleted messages notification");
	}

	@Override
	public void onError(Context context, String errorId) {
		Log.i(TAG, "Received error: " + errorId);
	}

	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		return super.onRecoverableError(context, errorId);
	}

	private static void generateNotification(Context context, String message) {
		int icon = R.drawable.ic_accept;
		long when = System.currentTimeMillis();
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(icon, message, when);
		String title = context.getString(R.string.app_name);
		Intent notificationIntent = new Intent(context, od_DangNhapActivity.class);
		// set intent so it does not start a new activity
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
		notification.setLatestEventInfo(context, title, message, intent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notificationManager.notify(0, notification);
	}

	private static void notification(Context context, String message, Class<?> activity,
			ArrayList<BasicNameValuePair> params) {
		int icon = R.drawable.ic_accept;
		long when = System.currentTimeMillis();
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(icon, message, when);
		String title = context.getString(R.string.app_name);
		Intent notificationIntent = new Intent(context, activity);
		if (params != null) {
			for (BasicNameValuePair p : params) {
				notificationIntent.putExtra(p.getName(), p.getValue());
			}
		}
		// set intent so it does not start a new activity
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
		notification.setLatestEventInfo(context, title, message, intent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notificationManager.notify(0, notification);
	}
}
